<template>
  <div class="app-container">
    <!-- 列表的查询条件参数 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="任务类型" prop="taskType">
        <el-select style="width: 150px" v-model="queryParams.taskType" placeholder="请选择任务类型" clearable>
          <el-option v-for="dict in taskTypeList" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="机构名称" prop="bankName">
        <el-input style="width: 150px" v-model="queryParams.bankName" placeholder="请输入分/支行名称" clearable8 />
      </el-form-item>
      <el-form-item label="摄像头名称" prop="channelRemark">
        <el-input style="width: 150px" v-model="queryParams.channelRemark" placeholder="请输入摄像头名称" clearable />
      </el-form-item>
      <el-form-item label="场景名称" prop="scenariosTypeList">
        <el-select v-model="queryParams.scenariosTypeList" multiple placeholder="请选择场景" style="width: 150px">
          <el-option v-for="dict in dict.type.task_scenarios_type" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable style="width:150px">
          <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 列表的查询功能按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['task:config:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['task:config:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['task:config:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-edit" size="mini" :disabled="multiple" @click="handleUse"
          v-hasPermi="['task:config:edit']">批量启用</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-edit" size="mini" :disabled="multiple" @click="handleDisable"
          v-hasPermi="['task:config:edit']">批量禁用</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleImport" v-hasPermi="['task:config:import']">导入分行任务</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleImportBankTask" v-hasPermi="['task:config:import']">导入总行任务</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleImportSubBankPanDian" v-hasPermi="['task:config:import']">导入分行盘点任务</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['task:config:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 列表数据 -->
    <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务类型" align="center" prop="taskType" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.taskType | handleTaskType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分行名称" align="center" prop="subBankName" width="80" />
      <!-- <el-table-column label="网点号" align="center" prop="bankCode" /> -->
      <el-table-column label="网点名称" align="center" prop="bankName" />
      <!-- <el-table-column label="设备IP" align="center" prop="equipmentIp" /> -->
      <el-table-column label="通道" align="center" prop="channelRemark" width="150" />
      <el-table-column label="开始时间" align="center" prop="startTime" />
      <el-table-column label="结束时间" align="center" prop="startEnd" />
      <el-table-column label="频率类型" align="center" prop="frequencyType" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.task_frequency_type" :value="scope.row.frequencyType" />
        </template>
      </el-table-column>
      <el-table-column label="应用场景" align="center" prop="scenariosType" width="300">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.task_scenarios_type" :value="scope.row.scenariosType" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="帧率" align="center" prop="fps" width="50" /> -->
      <el-table-column label="分割时间(秒)" align="center" prop="secondMerge" />
      <el-table-column prop="status" label="状态" align="center">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
          </template>
      </el-table-column>
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['task:config:edit']">修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['task:config:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改任务配置配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="650px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务类型" prop="taskType">
              <el-select v-model="form.taskType" placeholder="请选择任务类型" :disabled="!!form && !!form.taskConfigId">
                <el-option v-for="dict in taskTypeList" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="支行" prop="deptId">
              <treeselect v-model="form.deptId"
                @input="changeOrgCode"
                :disable-branch-nodes="true"
                 search-nested
                :options="deptOptions"
                :normalizer="normalizer"
                 placeholder="请选择支行"
                style="width:100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.taskType === '1' || form.taskType === '3'">
            <el-form-item label="摄像头通道" prop="cameraId">
              <el-select v-model="form.cameraId" clearable placeholder="请选择摄像头" style="width:100%" filterable>
                <el-option
                  v-for="item in videoOptions"
                  :key="item.cameraId"
                  :label="item.cameraName"
                  :value="item.cameraId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="摄像头通道" prop="channelKey" v-if="form.taskType === '2'">
              <el-select v-model="form.channelKey" @change="channelKeyChange" :key="videoOptionsFH.length" clearable placeholder="请选择摄像头" style="width:100%" filterable>
                <el-option
                  v-for="item in videoOptionsFH"
                  :key="item.channelKey"
                  :label="item.remark"
                  :value="item.channelKey">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="录像机编号" prop="equipmentId" v-if="form.taskType === '2'">
              <el-input v-model="form.equipmentId" placeholder="请选择录像机" suffix-icon="el-icon-caret-right"
                :readonly="true" @click.native="getEquipmentInfo" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属网点" prop="bankInfo" v-if="form.taskType === '2'">
              <el-input v-model="form.bankInfo" placeholder="所属网点信息" :disabled="true" />
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <!-- <el-col :span="12">
            <el-form-item label="设备IP" prop="equipmentIp" v-if="form.taskType === '2'">
              <el-input v-model="form.equipmentIp" placeholder="设备IP" :disabled="true" />
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="12">
            <el-form-item label="通道号" prop="channelKey" v-if="form.taskType === '2'">
              <el-select v-model="form.channelKey" placeholder="请选择通道">
                <el-option v-for="dict in channelKeyList" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="应用场景" prop="scenariosTypeList">
              <el-select v-model="form.scenariosTypeList" multiple placeholder="请选择场景">
                <el-option v-for="dict in dict.type.task_scenarios_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务频率" prop="frequencyType">
              <el-select v-model="form.frequencyType" placeholder="请选择频率" @change="handleFrequencyChange">
                <el-option v-for="dict in dict.type.task_frequency_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-show="timeFlag">
          <el-col :span="24">
            <el-form-item label="任务时间范围" prop="timeRange">
              <el-time-picker is-range v-model="form.timeRange" range-separator="至" start-placeholder="开始时间"
                end-placeholder="结束时间" placeholder="选择时间范围" value-format="HH:mm:ss">
              </el-time-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-show="dateFlag">
          <el-col :span="24">
            <el-form-item label="任务时间范围" prop="timeRange">
              <el-date-picker v-model="form.timeRange" type="datetimerange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期范围">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="帧率" prop="fps" v-if="form.taskType === '2'">
              <el-input-number v-model="form.fps" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分割时间(秒)" prop="secondMerge">
              <el-input-number v-model="form.secondMerge" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{
                  dict.label
                  }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="showDialog" width="1280px" title="请选择录像机" append-to-body>
      <!-- 列表的查询条件参数 -->
      <el-form :model="equipMentParamslistDataQuery" ref="showDialogQueryQueryForm" size="small" :inline="true"
        abel-width="88px">
        <el-form-item label="机构名称" prop="bankName">
          <el-input v-model="equipMentParamslistDataQuery.bankName" placeholder="请输入分/支行名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getEquipmentInfo">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetEquipMentParamslistDataQuery()">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="listData" @row-click="handleSelect" highlight-current-row @current-change="handleCurrentChange">
        <el-table-column prop="equipmentId" label="录像机编号" />
        <el-table-column prop="bankCode" label="网点号" />
        <el-table-column prop="bankName" label="网点名称" />
        <el-table-column prop="subBankCode" label="分行号" />
        <el-table-column prop="subBankName" label="分行名称" />
        <el-table-column prop="equipmentIp" label="设备IP" />
        <el-table-column prop="equipmentPort" label="设备端口" />
      </el-table>
      <pagination v-show="listDataTotal > 0" :total="listDataTotal" :page.sync="equipMentParamslistDataQuery.pageNum"
        :limit.sync="equipMentParamslistDataQuery.pageSize" @pagination="getList" />
    </el-dialog>

    <el-dialog title="批量导入分行任务" :visible.sync="dialogFormVisible" width="35%">
      <el-form ref="fileForm" label-width="100px">
        <el-form-item label="导入模版">
          <el-button size="small" type="primary" @click="downloadTemplate()">下载导入模版</el-button>
        </el-form-item>
        <el-form-item label="请选择文件">
          <el-upload class="upload-demo" ref="upload" accept=".xlsx, .xlsm, .xls" :auto-upload="false" action="#"
            :limit="1" :file-list="fileList" :on-change="handleChange" :on-exceed="handleExceed"
            :on-remove="handleRemove">
            <el-button size="small" type="success">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleImportExcel" :disabled="uploading">确定导入</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="批量导入总行任务" :visible.sync="dialogFormVisibleBankTask" width="35%">
      <el-form ref="fileForm" label-width="100px">
        <el-form-item label="导入模版">
          <el-button size="small" type="primary" @click="downloadTemplateBankTask()">下载导入模版</el-button>
        </el-form-item>
        <el-form-item label="请选择文件">
          <el-upload class="upload-demo" ref="upload" accept=".xlsx, .xlsm, .xls" :auto-upload="false" action="#"
            :limit="1" :file-list="fileListBankTask" :on-change="handleChangeBankTask" :on-exceed="handleExceedBankTask"
            :on-remove="handleRemoveBankTask">
            <el-button size="small" type="success">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleImportExcelBankTask" :disabled="uploadingBankTask">确定导入</el-button>
        <el-button @click="handleCancelBankTask">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="批量导入分行盘点任务" :visible.sync="dialogFormVisibleSubBankPanDian" width="35%">
      <el-form ref="fileForm" label-width="100px">
        <el-form-item label="导入模版">
          <el-button size="small" type="primary" @click="downloadTemplateSubBankPanDian()">下载导入模版</el-button>
        </el-form-item>
        <el-form-item label="请选择文件">
          <el-upload class="upload-demo" ref="upload" accept=".xlsx, .xlsm, .xls" :auto-upload="false" action="#"
            :limit="1" :file-list="fileListSubBankPanDian" :on-change="handleChangeSubBankPanDian" :on-exceed="handleExceedSubBankPanDian"
            :on-remove="handleRemoveSubBankPanDian">
            <el-button size="small" type="success">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleImportExcelSubBankPanDian" :disabled="uploadingSubBankPanDian">确定导入</el-button>
        <el-button @click="handleCancelSubBankPanDian">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
.app-container {
  ::v-deep.vue-treeselect__placeholder {
    font-size: 13px;
  }

  ::v-deep.vue-treeselect__control {
    height: 30px;
  }
}
</style>

<script>
import { listConfig, getConfig, delConfig, addConfig, updateConfig, importConfig, importConfigBankTask, importConfigSubBankPanDian, updateConfigStatus } from "@/api/iis/taskconfig";
import { cameraInfoList } from "@/api/modelTest/imageSelectedArea";
import { listConfig as channelList } from "@/api/iis/channel";
import { listConfig as equipmentListConfig } from "@/api/iis/equipment";
import { listDept } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { blobValidate } from "@/utils/ruoyi";
import { Message } from 'element-ui'
import errorCode from '@/utils/errorCode'

export default {
  name: "Config",
  dicts: ['sys_normal_disable', 'task_frequency_type', "task_scenarios_type"],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 任务配置配置表格数据
      configList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bankName: "",
        channelRemark: "",
        scenariosTypeList: [],
        equipmentId: null,
        startTime: null,
        startEnd: null,
        frequencyType: null,
        scenariosType: null,
        fps: null,
        secondMerge: null,
        status: "0",
        taskType: "",
      },
      // 表单参数
      form: {
        taskType: '',
        cameraId: null,
        bankCode: null,
        deptId: null,
        channelKey: null
      },
      formTemp: {},
      // 表单校验
      rules: {
        equipmentId: [
          { required: true, message: "设备编号不能为空", trigger: "blur" }
        ],
        channelKey: [
          { required: true, message: "请选择摄像头", trigger: "blur" }
        ],
        timeRange: [
          { required: true, message: "任务时间范围不能为空", trigger: "blur" }
        ],
        scenariosType: [
          { required: true, message: "应用场景不能为空", trigger: "blur" }
        ],
        frequencyType: [
          { required: true, message: "频率类型不能为空", trigger: "blur" }
        ],
        fps: [
          { required: true, message: "帧率不能为空", trigger: "blur" }
        ],
        secondMerge: [
          { required: true, message: "分割时间不能为空", trigger: "blur" }
        ],
        cameraId: {
          required: true, message: "摄像头不能为空", trigger: "blur"
        },
        deptId: {
          required: true, message: "机构不能为空", trigger: "blur"
        },
        taskType: {
          required: true, message: "任务类型不能为空", trigger: "blur"
        },
      },
      showDialog: false,
      showDialogQuery: false,
      listData: [],
      listDataQuery: [],
      // equipMentqueryParamslistDataQuery: {
      //   pageNum: 1,
      //   pageSize: 10,
      //   bankName: ""
      // },
      equipMentParamslistDataQuery: {
        pageNum: 1,
        pageSize: 10,
        bankName: ""
      },
      videoOptions: [],
      videoOptionsFH: [],
      deptList: [],
      listDataTotal: [],
      // listDataQueryTotal: [],
      deptOptions: [],
      timeFlag: true,
      dateFlag: false,
      channelKeyList: [],
      taskTypeList: [
        {
          value: "1",
          label: "总行任务"
        },
        {
          value: "2",
          label: "分行任务"
        },
        {
          value: "3",
          label: "浩云分行"
        }
      ],
      //excel批量导入功能
      dialogFormVisible: false,
      dialogFormVisibleBankTask: false,
      fileList: [],  //文件列表
      fileListBankTask: [],  //文件列表
      file: {},
      fileBankTask: {},
      uploading: true, //默认置灰确定导入按钮
      uploadingBankTask: true, //默认置灰确定导入按钮
      dialogFormVisibleSubBankPanDian: false,
      fileListSubBankPanDian: [],
      fileSubBankPanDian: {},
      uploadingSubBankPanDian: true // 置灰确定导入按钮
    };
  },
  // watch: {
  //   'form.equipmentId': {
  //     handler(val) {
  //       console.log('equipmentId changed to:', val);
  //       if (val) {
  //         this.getChannelKeyList();
  //       }
  //       // 处理逻辑
  //     },
  //     immediate: true // 如果初始值已经存在，则会立即触发一次
  //   }
  // },
  filters: {
    handleTaskType(taskType) {
      if (taskType === "1") {
        return "总行任务";
      } else if (taskType === "2") {
        return "分行任务";
      } else if (taskType === "3") {
        return "浩云分行";
      }
    },
  },
  created() {
    this.getList();
    listDept().then(response => {
      this.deptList = response.data
      this.deptOptions = this.handleTree(response.data, "deptId");
    });
  },
  methods: {
    channelKeyChange(channelKey){
      // this.$forceUpdate();
    },
    changeOrgCode(deptId) {
      // 改变部门时，清空摄像头列表
      this.videoOptions = []
      this.videoOptionsFH = []
      // this.form.cameraId = null
      const dept = this.deptList.find(item => item.deptId === deptId)
      if (!dept || !dept.deptCode) {
        return false
      }
      const self = this;
      if (this.form.taskType === '1' || this.form.taskType === '3') {
        let queryParams = {
          deptCode: dept.deptCode
        };
        cameraInfoList(queryParams).then(response => {
          self.videoOptions = response.rows;
        });
      }else if (this.form.taskType === '2') {
        let queryParams = {
          bankCode: dept.deptCode,
          status: "0",
          pageSize: 1000
        };
        equipmentListConfig(queryParams).then(response => {
          self.videoOptionsFH = response.rows;
          self.videoOptionsFH.forEach(item => {
            item.channelKey = item.channelId + ""
          });
          const camera = self.videoOptionsFH.find(item => {
            return item.channelKey === self.form.channelKey
          })
          if (!camera || !camera.channelKey) {
            this.form.channelKey = ""
          }
        });
      }
    },
    // getChannelKeyList() {
    //   const queryParams = {
    //     pageNum: 1,
    //     pageSize: 100,
    //     equipmentId: this.form.equipmentId
    //   }
    //   self = this
    //   channelList(queryParams).then(response => {
    //     const rows = response.rows;
    //     self.channelKeyList = rows.map((item) => {
    //       return {
    //         value: item.channelId + "",
    //         label: item.remark
    //       }
    //     })
    //     self.form.channelKey = "";
    //     const channelKey = self.formTemp.channelKey
    //     console.log("channelKey--->", channelKey, self.channelKeyList);
    //     if (self.formTemp.channelKey) {
    //       let channelItem = {}
    //       self.channelKeyList.forEach(item => {
    //         if (item.value === channelKey) {
    //           channelItem = item;
    //           return
    //         }
    //       })
    //       if (channelItem) {
    //         self.form.channelKey = channelItem.value;
    //         // self.formTemp = {}
    //       }
    //     }
    //   });
    // },
    /** 查询任务配置配置列表 */
    getList() {
      this.loading = true;
      let queryParams = Object.assign({}, this.queryParams);
      if (queryParams.scenariosTypeList && queryParams.scenariosTypeList.length > 0) {
        queryParams.scenariosType = queryParams.scenariosTypeList.join(",");
      }
      delete queryParams.scenariosTypeList;
      listConfig(queryParams).then(response => {
        this.configList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        taskType: "2",
        taskConfigId: null,
        equipmentId: null,
        startTime: null,
        startEnd: null,
        frequencyType: '01',
        scenariosType: '01',
        fps: null,
        secondMerge: "60",
        status: '0',
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        channelKey: null,
        timeRange: null,
        channelKey: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      console.log("this.queryParams:", this.queryParams)
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.taskConfigId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加任务配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const taskConfigId = row.taskConfigId || this.ids
      const self = this
      getConfig(taskConfigId).then(response => {
        response.data.channelKey = response.data.channelKey + "";
        // response.data.bankCode = "2109";
        if (response.data.taskType === "1" || response.data.taskType === "3") {
          // 总行任务数据回显
          self.deptList.find(item => {
            // 反显总行任务的-支行选项
            if (item.deptCode === response.data.bankCode) {
              response.data.deptId = item.deptId
            }
          });
          // 根据支行code，反查获取摄像头列表
          cameraInfoList({
            deptCode: response.data.bankCode
          }).then(res => {
            self.videoOptions = res.rows;
            self.formTemp = JSON.parse(JSON.stringify(response.data));
            self.form = JSON.parse(JSON.stringify(response.data));
            self.open = true;
            self.title = "修改任务配置";
          });
        } else if (response.data.taskType === "2") {
          self.deptList.find(item => {
            // 反显总行任务的-支行选项
            if (item.deptCode === response.data.bankCode) {
              response.data.deptId = item.deptId
            }
          });
          let queryParams = {
            bankCode: response.data.bankCode,
            status: "0"
          };
          equipmentListConfig(queryParams).then(res => {
            self.videoOptionsFH = res.rows;
            self.videoOptionsFH.forEach(item => {
              item.channelKey = item.channelId + "";
            });
            // 分行任务数据回显
            self.$nextTick(() => {
              self.formTemp = JSON.parse(JSON.stringify(response.data));
              self.form = JSON.parse(JSON.stringify(response.data));
            });

            // 当前任务的配置明细
            self.open = true;
            self.title = "修改任务配置";
          });
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log("timeRange:", this.form.timeRange);
      let form = Object.assign({}, this.form);
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (form.deptId) {
            // 总行任务
            const dept = this.deptList.find(item => item.deptId === form.deptId)
            if (!dept || !dept.deptCode) {
              return false
            }
            form.bankCode = dept.deptCode
          }
          if (form.taskType === "2" && form.channelKey) {
            this.videoOptionsFH.map(item => {
              if (item.channelKey === form.channelKey) {
                form.equipmentId = item.equipmentId
                form.equipmentIp = item.equipmentIp
              }
            })
          }
          if (form.taskConfigId != null) {
            updateConfig(form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addConfig(form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const taskConfigIds = row.taskConfigId || this.ids;
      this.$modal.confirm('是否确认删除任务配置？').then(function () {
        return delConfig(taskConfigIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    // 批量使用
    handleUse() {
      const taskConfigIds = this.ids;
      this.$modal.confirm('是否确认批量启用任务？').then(function () {
        return updateConfigStatus("0", taskConfigIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("启用成功");
      }).catch(() => { });
    },
    // 批量禁用
    handleDisable() {
      const taskConfigIds = this.ids;
      this.$modal.confirm('是否确认批量禁用任务？').then(function () {
        // return delConfig(taskConfigIds);
        return updateConfigStatus("1", taskConfigIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("禁用成功");
      }).catch(() => { });
    },

    /** 批量导入操作 */
    handleImport() {
      this.dialogFormVisible = true;
      this.fileList = [];
      this.file = {};
      this.uploading = true; // 置灰确定导入按钮
    },
    handleImportBankTask() {
      this.dialogFormVisibleBankTask = true;
      this.fileListBankTask = [];
      this.fileBankTask = {};
      this.uploadingBankTask = true; // 置灰确定导入按钮
    },
    handleImportSubBankPanDian() {
      this.dialogFormVisibleSubBankPanDian = true;
      this.fileListSubBankPanDian = [];
      this.fileSubBankPanDian = {};
      this.uploadingSubBankPanDian = true; // 置灰确定导入按钮
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('task/config/export', {
        ...this.queryParams
      }, `config_${new Date().getTime()}.xlsx`)
    },
    downloadTemplateBankTask() {
      this.download('task/config/downloadTemplate', {
        taskType: '1'
      }, `templateBankTask.xlsx`)
    },
    downloadTemplate() {
      this.download('task/config/downloadTemplate', {
        taskType: '2'
      }, `templateSubBankTask.xlsx`)
    },
    downloadTemplateSubBankPanDian() {
      this.download('task/config/downloadTemplate', {
        taskType: '3'
      }, `templateSubBankPanDian.xlsx`)
    },
    handleSelect(row) {
      this.$refs.form.clearValidate(['equipmentId']);
      this.form.equipmentId = row.equipmentId;
      this.form.equipmentIp = row.equipmentIp;
      this.form.bankInfo = row.bankCode + '-' + row.bankName;
      this.showDialog = false;
    },
    handleSelectQuery(row) {
      this.queryParams.equipmentId = row.equipmentId;
      this.showDialogQuery = false;
    },
    handleCurrentChange(currentRow) {
      this.selectedRow = currentRow;
    },
    getEquipmentInfo() {
      this.loading = true;

      equipmentListConfig(this.equipMentParamslistDataQuery).then(response => {
        this.listData = response.rows;
        this.listDataTotal = response.total;
        this.loading = false;
      });
      this.showDialog = true;
    },
    resetEquipMentParamslistDataQuery() {
      this.equipMentParamslistDataQuery = {
        pageNum: 1,
        pageSize: 10,
        bankName: ""
      }
      this.getEquipmentInfo()
    },
    // getEquipmentInfoQuery() {
    //   this.loading = true;
    //   equipmentListConfig(this.equipMentqueryParamslistDataQuery).then(response => {
    //       this.listDataQuery = response.rows;
    //       this.listDataQueryTotal = response.total;
    //       this.loading = false;
    //   });
    //   this.showDialogQuery = true;
    // },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    handleFrequencyChange(value) {
      this.form.timeRange = null;
      if (value === '01') {
        this.timeFlag = true;
        this.dateFlag = false;
      } else if (value === '02') {
        this.timeFlag = false;
        this.dateFlag = true;
      } else {
        this.timeFlag = false;
        this.dateFlag = false;
      }
    },
    //excel批量打入功能
    handleChange(file) {     //(file,fileList)参数
      this.uploading = false;
      this.file = file;
    },
    handleChangeBankTask(file) {     //(file,fileListBankTask)参数
      this.uploadingBankTask = false;
      this.fileBankTask = file;
    },
    handleChangeSubBankPanDian(file) {
      this.uploadingSubBankPanDian = false;
      this.fileSubBankPanDian = file;
    },
    //文件超出个数限制
    handleExceed() {
      this.$message.warning("仅允许上传一个文件！");
    },
    handleExceedBankTask() {
      this.$message.warning("仅允许上传一个文件！");
    },
    handleExceedSubBankPanDian() {
      this.$message.warning("仅允许上传一个文件！");
    },
    //移除文件
    handleRemove() {
      this.uploading = true;
    },
    handleRemoveBankTask() {
      this.uploadingBankTask = true;
    },
    handleRemoveSubBankPanDian() {
      this.uploadingSubBankPanDian = true;
    },
    //取消
    handleCancel() {
      this.file = {};
      this.fileList = [];
      this.dialogFormVisible = false;
      this.uploading = true;
    },
    handleCancelBankTask() {
      this.fileBankTask = {};
      this.fileListBankTask = [];
      this.dialogFormVisibleBankTask = false;
      this.uploadingBankTask = true;
    },
    handleCancelSubBankPanDian() {
      this.fileSubBankPanDian = {};
      this.fileListSubBankPanDian = [];
      this.dialogFormVisibleSubBankPanDian = false;
      this.uploadingSubBankPanDian = true;
    },
    //导入excel
    handleImportExcel() {
      if (!this.file.size) {
        this.$message.warning("请选择上传的文件");
        return;
      }
      this.uploading = true;
      let formData = new FormData();
      formData.append("file", this.file.raw);
      importConfig(formData).then(res => {
        this.$modal.msgSuccess("导入成功");
        this.uploading = false;  //调用接口
        this.dialogFormVisible = false;
        this.getList();
      });
    },
    handleImportExcelBankTask() {
      if (!this.fileBankTask.size) {
        this.$message.warning("请选择上传的文件");
        return;
      }
      this.uploadingBankTask = true;
      let formData = new FormData();
      formData.append("file", this.fileBankTask.raw);
      importConfigBankTask(formData).then(res => {
        this.$modal.msgSuccess("导入成功");
        this.uploadingBankTask = false;  //调用接口
        this.dialogFormVisibleBankTask = false;
        this.getList();
      });
    },
    handleImportExcelSubBankPanDian() {
      if (!this.fileSubBankPanDian.size) {
        this.$message.warning("请选择上传的文件");
        return;
      }
      this.uploadingSubBankPanDian = true;
      let formData = new FormData();
      formData.append("file", this.fileSubBankPanDian.raw);
      importConfigSubBankPanDian(formData)
      .then(async (data) => {
        const isBlob = blobValidate(data);
        if (data.type !== "application/json" && isBlob) {
          const blob = new Blob([data])
          saveAs(blob, "导入盘点任务失败行.xlsx")
          Message.error("导入判断任务有失败项，错误信息请查看结果文件");
        } else {
          const resText = await data.text();
          const rspObj = JSON.parse(resText);
          console.log(resText);
          const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
          if (rspObj.code !== 200) {
            Message.error(errMsg);
          }else {
            Message.success(errMsg);
          }
        }
        this.uploadingSubBankPanDian = false;  //调用接口
        this.dialogFormVisibleSubBankPanDian = false;
        this.getList();
      }).catch((r) => {
        console.error(r)
        Message.error('导入任务出现错误，请联系管理员！')
      });
    }
  }
};
</script>
